//
//  DLSmsLoginView.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/11/23.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLSmsLoginView.h"


@interface DLSmsLoginView()


@end

@implementation DLSmsLoginView

- (instancetype) initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        [self layoutSubControls];
    }
    return self;
}

- (void) layoutSubControls {
    
    //手机号输入框
    CGFloat phoneTFW = self.width - 80;
    CGFloat phoneTFH = 50;
    
    
    UILabel *phoneTFLeftLable = [UILabel new];
    phoneTFLeftLable.frame = CGRectMake(0, 0, 80, phoneTFH);
    phoneTFLeftLable.text = @"账    号：";
    phoneTFLeftLable.textAlignment = NSTextAlignmentLeft;
    phoneTFLeftLable.font = kSystemFont(18);
    phoneTFLeftLable.textColor = kDLNormalBlackColor;
    [self addSubview:phoneTFLeftLable];
    
    UITextField *phoneTF = [UITextField new];
    phoneTF.frame = CGRectMake(phoneTFLeftLable.right, phoneTFLeftLable.top, phoneTFW, phoneTFH);
    phoneTF.borderStyle = UITextBorderStyleNone;
    phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    phoneTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    phoneTF.font = kSystemFont(18);
    phoneTF.placeholder = @"请输入账号";
    [phoneTF addTarget:self action:@selector(phoneTFTextChange:) forControlEvents:UIControlEventEditingChanged];
    [self addSubview:phoneTF];
    self.phoneTF = phoneTF;
    
    UIView *lineView = [UIView new];
    lineView.frame = CGRectMake(phoneTF.left, phoneTF.bottom, phoneTF.width, 1);
    lineView.backgroundColor = kDLNormalBlackColor;
    [self addSubview:lineView];
    
    
    UILabel *smscodeTFLeftLable = [UILabel new];
    smscodeTFLeftLable.frame = CGRectMake(phoneTFLeftLable.left, lineView.bottom, phoneTFLeftLable.width, phoneTFH);
    smscodeTFLeftLable.text = @"验证码：";
    smscodeTFLeftLable.textAlignment = NSTextAlignmentLeft;
    smscodeTFLeftLable.font = kSystemFont(18);
    smscodeTFLeftLable.textColor = kDLNormalBlackColor;
    [self addSubview:smscodeTFLeftLable];
    
    //验证码
    UITextField *smscodeTF = [UITextField new];
    smscodeTF.frame = CGRectMake(smscodeTFLeftLable.right, smscodeTFLeftLable.top, phoneTF.width, phoneTFH);
    smscodeTF.borderStyle = UITextBorderStyleNone;
    smscodeTF.keyboardType = UIKeyboardTypeNumberPad;
    smscodeTF.font = kSystemFont(18);
    smscodeTF.placeholder = @"请输入验证码";
    [smscodeTF addTarget:self action:@selector(smscodeTFTextChange:) forControlEvents:UIControlEventEditingChanged];
    [self addSubview:smscodeTF];
    self.smscodeTF = smscodeTF;
    
    UIButton *getVerifyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    getVerifyButton.frame = CGRectMake(self.width - 95, lineView.bottom, 95, 50);
    getVerifyButton.backgroundColor = [UIColor whiteColor];
    [getVerifyButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    getVerifyButton.titleLabel.font = kSystemFont(13);
    [getVerifyButton setTitleColor:kDLNormalGrayColor forState:UIControlStateNormal];
    [getVerifyButton setTitleColor:kDLBtnNormalBgColor forState:UIControlStateDisabled];
    [getVerifyButton addTarget:self action:@selector(codeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:getVerifyButton];
    self.smsCodeBtn = getVerifyButton;
}

- (void)phoneTFTextChange:(UITextField *)textField {
    
    if (textField.text.length >11) {
        NSString *str = textField.text;
        textField.text = [str substringToIndex:11];
    }
}


- (void)smscodeTFTextChange:(UITextField *)textField {
    
    if (textField.text.length >6) {
        NSString *str = textField.text;
        textField.text = [str substringToIndex:6];
    }
}

- (void) codeBtnClick {
    
    if (self.phoneTF.text.length < 11) {
        
        //        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
        //        hud.labelText = @"请输入手机号";
        //        [hud show:YES];
        //        [hud hide:YES afterDelay:0.8];
        
        [[UIApplication sharedApplication].keyWindow makeToast:@"请输入正确的手机号" duration:1 position:CSToastPositionCenter];
        return;
    }
    
    [self endEditing:YES];
    
    [self checkPhoneNumIsExist];
    
}
- (void) checkPhoneNumIsExist {
    //检查手机号是否存在
    NSString *postUrl = HTTPCheckPhoneNumIsExist;
    NSDictionary *postDic = @{
                              @"mobile" : self.phoneTF.text
                              };
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
            
            NSDictionary *dic = responseObject[@"result"];
            NSString *isExist = [NSString stringWithFormat:@"%@", dic[@"exits"]];
            if ([isExist isEqualToString:@"1"]) {
                [self getImageVerify];
            } else {
                kShowRequestMsg(kSafeString(responseObject[@"message"]));
            }
        } else {
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
        }
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
}
- (void) getImageVerify {
    
    DLImageVerifyAlertView *imageVerifyAlertView = [DLImageVerifyAlertView showSmsVerifyAlert];
    imageVerifyAlertView.alertViewType = DLAlertViewType_allScreen;
    [imageVerifyAlertView alertShow];
    imageVerifyAlertView.phoneNum = self.phoneTF.text;
    imageVerifyAlertView.smscodeTF.text = @"";
    self.imageVerifyAlertView = imageVerifyAlertView;
    
    [imageVerifyAlertView getImageVerifyCode];
    
    imageVerifyAlertView.nextButtonClickBlock = ^{
        
        [self getSmsCode];
    };
}

- (void) getSmsCode {
    
    //请求接口
    NSString *getUrl = HTTPGetSMS;
    NSDictionary *getDic = @{
                             @"mobile" : self.phoneTF.text,
                             @"condition" : @(2)
                             };
    
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:getUrl parameters:getDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
            [self openCountdown];
        } else {
            
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
        }
        
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
    
}

- (void)openCountdown{
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [self.smsCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                self.smsCodeBtn.enabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self.smsCodeBtn setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                self.smsCodeBtn.enabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
